<template>
  <div class="container">
    <section class="flex flex-wrap f-ptp10">
      <el-input class="f-mrt20 f-mbt10 f-w120" v-model="userId" placeholder="用户id" clearable></el-input>
      <el-input class="f-mrt20 f-mbt10 f-w120" v-model="mobileNo" placeholder="手机号" clearable></el-input>
      <el-input class="f-mrt20 f-mbt10 f-w120" v-model="nickName" placeholder="姓名" clearable></el-input>
      <el-input class="f-mrt20 f-mbt10 f-w200" v-model="idCardNo" placeholder="身份证号码" clearable></el-input>
      <!-- <el-input class='f-mrt20 f-mbt10 f-w120' v-model="date" placeholder="注册时间开始-结束"></el-input> -->
      <el-date-picker
        class="f-mrt20"
        v-model="date"
        type="daterange"
        range-separator="至"
        start-placeholder="注册开始日期"
        end-placeholder="结束日期"
      ></el-date-picker>
      <el-select class="f-mrt20 f-mbt10 f-w120" v-model="vip" clearable placeholder="请选择">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
      <el-button @click="getUserList" type="primary">查询</el-button>
      <!-- <el-button @click="exportExcel" type="success">导出exce(当前页)</el-button> -->
      <el-button @click="exportBtnClickEvent" type="success">导出excel</el-button>
    </section>
    <div>
      <el-table
        id="table-content"
        :data="userList"
        border
        :header-cell-style="{
            'background-color': '#fafafa'
        }"
        style="width: 100%; min-width: 1000px"
      >
        <el-table-column prop="userId" label="用户id" width="180"></el-table-column>
        <el-table-column prop="mobileNo" label="手机号" width="180"></el-table-column>
        <el-table-column prop="nickName" label="姓名" width="180"></el-table-column>
        <el-table-column prop="idCardNo" label="身份证号码" width="180"></el-table-column>
        <el-table-column prop="money" label="账户余额" width="180"></el-table-column>
        <el-table-column prop="isVip" label="是否会员" width="180">
          <template slot-scope="scope">
            <span>{{scope.row.isVip == 1 ? "是" : "否"}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" width="180">
          <template slot-scope="scope">
            <span>{{ tranDate(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="manage" label="管理">
          <template slot-scope="scope">
            <span @click="editBtnClickEvent(scope.row)" class="s-c-green f-csp f-mrt10">编辑</span>
            <span @click="showBillBtnClickEvent(scope.row)" class="s-c-green f-csp f-mrt10">查看账户</span>
            <span
              @click="enableBtnClickEvent(scope.row)"
              class="f-csp f-mrt10"
              :class="scope.row.state == 'frozen' ? 's-c-green' : 's-c-red'"
            >{{scope.row.state == 'frozen' ? '启用' : '禁用'}}</span>
            <span
              @click="resetPasswordBtnClickEvent(scope.row)"
              class="s-c-green f-csp f-mrt10"
            >重置密码</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="f-ptp20 f-pbt20 f-oh">
        <el-pagination
          class="f-fr"
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-size="pageSize"
          background
          layout="total, prev, pager, next, jumper"
          :total="totalCount"
        ></el-pagination>
      </div>
    </div>

    <el-dialog title="编辑" :visible.sync="showEdit" center width="560px">
      <div>
        <div class="flex edit-item">
          <label for>手机号：</label>
          <el-input v-model="editPhone" type="text" placeholder="手机号码"/>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showEdit = false">取 消</el-button>
        <el-button type="primary" @click="editOkBtnClickEvent">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="重置密码"
      :visible.sync="showResetPasswrod"
      center
      :before-close="handleClose"
      width="560px"
    >
      <div>
        <div class="flex edit-item f-mbt20">
          <label for>新密码：</label>
          <el-input
            type="password"
            v-model="resetPassword"
            maxlength="10"
            placeholder="输入6-10位数新密码"
          />
        </div>
        <div class="flex edit-item">
          <label for>确认密码：</label>
          <el-input type="password" v-model="resetRePassword" maxlength="10" placeholder="确认密码"/>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showResetPasswrod = false">取 消</el-button>
        <el-button type="primary" @click="resetPasswordConfirm">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="查看账户"
      :visible.sync="showBill"
      center
      :before-close="handleBillClose"
      width="660px"
    >
      <div>
        <table class="table" border="1" bordercolor="#ccc" width="600">
          <!-- <tr>
            <th>余额</th>
            <td width="200">{{billInfo.totalAmount}}</td>
            <td width="150"></td>
          </tr>-->
          <tr>
            <th>冻结资金</th>
            <td>{{billInfo.frozenAmount}}</td>
            <td></td>
          </tr>
          <tr>
            <th>历史余额（只增不减）</th>
            <td>{{billInfo.totalAmountHistory}}</td>
            <td></td>
          </tr>
          <tr>
            <th>可用余额</th>
            <td>
              <span v-if="!isEditBill">{{billInfo.usableAmount}}</span>
              <el-input v-else v-model="usableAmount"/>
            </td>
            <td>
              <span class="table_btn" v-if="!isEditBill" @click="isEditBill=true">修改</span>
              <span class="table_btn" v-if="isEditBill" @click="isEditBill=false">取消</span>
              <span class="table_btn" v-if="isEditBill" @click="billSubmit">提交</span>
            </td>
          </tr>
          <tr>
            <th>历史提现金额数量（只增不减）</th>
            <td>{{billInfo.withdrawAmountHistory}}</td>
            <td></td>
          </tr>
        </table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleBillClose">取 消</el-button>
        <el-button type="primary" @click="handleBillClose">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import axios from 'axios';
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
  name: "UserManage",
  data() {
    return {
      isEditBill: false, // 是否修改账户余额
      bili_userId: null,
      billInfo: {},
      usableAmount: null,
      showBill: false,

      showEdit: false, // 编辑弹窗显示、隐藏
      showResetPasswrod: false, // 重置弹窗显示、隐藏
      resetPassword: "", // 新密码
      resetRePassword: "", // 确认密码
      editItem: null,
      editPhone: "",
      mobileNo: "",
      vip: "",
      nickName: "",
      userId: "",
      idCardNo: "",
      date: "",
      options: [
        {
          value: "-1",
          label: "全部"
        },
        {
          value: "1",
          label: "会员"
        },
        {
          value: "0",
          label: "非会员"
        }
      ],
      currentPage: 1,
      totalCount: 0,
      pageSize: 10,
      userList: []
    };
  },
  created: function() {
    this.getUserList();
  },
  methods: {
    // 导出按钮点击事件
    exportBtnClickEvent() {
      if (this.totalCount > 0) {
        this.getAllList();
      }
    },
    // 导出所有数据
    exportAllExcel(list) {
      console.log('list::', list);
      let sheet1 = {
            "!ref": "A1:" + XLSX.utils.encode_cell({c: 6, r: list.length + 1}),
            A1: { v: "用户id", t: "s" },
            B1: { v: "手机号码", t: "s" },
            C1: { v: "昵称", t: "s" },
            D1: { v: "身份证号码", t: "s" },
            E1: { v: "账号余额", t: "s" },
            F1: { v: "是否会员", t: "s" },
            G1: { v: "注册时间", t: "s" },
          }
      for(let i = 0; i < list.length; i++) {
        let column_1 = XLSX.utils.encode_cell({c: 0, r: i + 1});
        let column_2 = XLSX.utils.encode_cell({c: 1, r: i + 1});
        let column_3 = XLSX.utils.encode_cell({c: 2, r: i + 1});
        let column_4 = XLSX.utils.encode_cell({c: 3, r: i + 1});
        let column_5 = XLSX.utils.encode_cell({c: 4, r: i + 1});
        let column_6 = XLSX.utils.encode_cell({c: 5, r: i + 1});
        let column_7 = XLSX.utils.encode_cell({c: 6, r: i + 1});
        sheet1[column_1] = {
          v: list[i].id,
          t: "s"
        }
        sheet1[column_2] = {
          v: list[i].mobileNo,
          t: "s"
        }
        sheet1[column_3] = {
          v: list[i].nickName,
          t: "s"
        }
        sheet1[column_4] = {
          v: '',
          t: "s"
        }
        sheet1[column_5] = {
          v: list[i].money,
          t: "s"
        }
        sheet1[column_6] = {
          v: list[i].isVip == 1 ? '是' : '否',
          t: "s"
        }
        sheet1[column_7] = {
          v: list[i].createTime,
          t: "d"
        }

      }
      console.log('sheet1:::', sheet1);
      const workbook = {
        FileName: "export.xlsx",
        SheetNames: ["Sheet1"],
        Sheets: {
          Sheet1: sheet1
        }
      };
      const workbookOut = XLSX.write(workbook, {
        bookType: "xlsx",
        bookSST: false,
        type: "array"
      });
      var date = new Date();
      var fileName = "用户表_" + date.getFullYear() + '_' + (date.getMonth() + 1) + '_' + date.getDate() + ".xlsx";
      try {
        FileSaver.saveAs(
          new Blob([workbookOut], {
            type: "application/octet-stream"
          }),
          fileName
          // "user.xlsx"
        ); //trade-publish.xlsx 为导出的文件名
      } catch (e) {
        console.log(e, workbookOut);
      }
      return workbookOut;
    },
    // 导出当前页面数据
    exportExcel() {
      let et = XLSX.utils.table_to_book(
        document.getElementById("table-content")
      ); //此处传入table的DOM节点
      console.log("et:::", et);
      let etout = XLSX.write(et, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      var fileName = "用户表_" + this.currentPage + ".xlsx";
      try {
        FileSaver.saveAs(
          new Blob([etout], {
            type: "application/octet-stream"
          }),
          fileName
          // "user.xlsx"
        ); //trade-publish.xlsx 为导出的文件名
      } catch (e) {
        console.log(e, etout);
      }
      return etout;
    },
    // 打印
    printContent() {
      let wpt = document.getElementById("table-content");
      let newContent = wpt.innerHTML;
      let oldContent = document.body.innerHTML;

      document.body.innerHTML = newContent;
      window.print(); //打印方法
      window.localtion.reload();
      document.body.innerHTML = oldContent;
    },
    billSubmit() {
      if (this._utils.isEmpty(this.usableAmount)) {
        this.$message.warning("请输入金额");
        return;
      }
      var usableAmount = this.usableAmount;
      usableAmount = usableAmount.replace(/^00*/, "0");
      console.log("usableAmount::", usableAmount);
      var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
      if (!reg.test(usableAmount)) {
        this.$message.warning("请输入正确金额！");
        return;
      }
      this.updateBill(usableAmount);
    },
    updateBill(usableAmount) {
      this.$store
        .dispatch("UPDATE_USER_BILL", {
          id: this.billInfo.id,
          usableAmount
        })
        .then(res => {
          if (res.data.retCode == 0) {
            console.log("this.res::", res);
            this.getBill();
            this.isEditBill = false;
          } else {
            res.data.errorMsg && this.$message.warning(res.data.errorMsg);
          }
        });
    },
    handleBillClose() {
      console.log("befor");
      this.showBill = false;
      this.isEditBill = false; // 是否修改账户余额
      this.bili_userId = null;
      this.billInfo = {};
      this.usableAmount = null;
    },
    showBillBtnClickEvent(item) {
      console.log("item::", item);
      this.bili_userId = item.userId;
      this.getBill();
      this.showBill = true;
    },
    getBill() {
      this.$store
        .dispatch("GET_USER_BILL_BY_USER_ID", {
          userId: this.bili_userId
        })
        .then(res => {
          if (res.data.retCode == 0) {
            console.log("res::", res);
            this.billInfo = res.data.data;
            this.usableAmount = res.data.data.usableAmount;
          } else {
            this.data.errorMsg && this.$message.warning(res.data.errorMsg);
          }
        });
    },
    tranDate(date) {
      return this._utils.format(date, "yyyy-mm-dd");
    },
    // 重置密码按钮点击事件
    resetPasswordBtnClickEvent(row) {
      this.showResetPasswrod = true;
      this.editItem = row;
    },

    // 重置密码弹窗-确认按钮点击事件
    resetPasswordConfirm() {
      if (this._utils.isEmpty(this.resetPassword)) {
        this.$message.warning("请输入新密码！");
        return;
      }
      if (this.resetPassword.length < 6 || this.resetPassword.length > 10) {
        this.$message.warning("请输入6-10位数新密码！");
        return;
      }
      if (this.resetPassword != this.resetRePassword) {
        this.$message.warning("两次输入的密码不一致！");
        return;
      }
      this.updataUserInfo(
        {
          id: this.editItem.id,
          password: this.resetPassword
        },
        () => {
          this.$message.success("重置成功！");
          this.showResetPasswrod = false;
          this.getUserList();
        }
      );
    },

    // 重置密码弹窗-关闭前处理函数
    handleClose() {
      this.editItem = "";
      this.resetPassword = "";
      this.resetRePassword = "";
      this.showResetPasswrod = false;
    },
    // 启用按钮点击事件
    enableBtnClickEvent(row) {
      console.log("row::", row);
      if (row.state == "normal") {
        this.$confirm("是否禁用该用户？", "禁用", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.updataUserInfo(
            {
              id: row.id,
              state: "frozen"
            },
            () => {
              this.$message.success("已禁用！");
              this.getUserList();
            }
          );
        });
      } else {
        this.$confirm("是否启用该用户？", "启用", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.updataUserInfo(
            {
              id: row.id,
              state: "normal"
            },
            () => {
              this.$message.success("已启用！");
              this.getUserList();
            }
          );
        });
      }
    },
    // 编辑按钮点击事件
    editBtnClickEvent(row) {
      console.log("row:::", row);
      this.showEdit = true;
      this.editItem = row;
      this.editPhone = row.mobileNo;
    },
    // 编辑-确定按钮点击事件
    editOkBtnClickEvent() {
      if (!this._utils.isPhoneNum(this.editPhone)) {
        this.$message.warning("请输入正确的手机号码！");
        return;
      }
      this.updataUserInfo(
        {
          id: this.editItem.id,
          mobileNo: this.editPhone
        },
        () => {
          this.$message.success("编辑成功！");
          this.showEdit = false;
          this.editPhone = "";
          this.getUserList();
        }
      );
    },
    // 更新用户信息
    updataUserInfo(params, callback) {
      this.$store.dispatch("UPDATE_USER", params).then(res => {
        if (res.data.retCode == 0) {
          callback && callback();
        } else {
          res.data.errorMsg && this.$message.warning(res.data.errorMsg);
        }
      });
    },
    getUserList() {
      const _this = this;
      const page = this.currentPage - 1;
      const params = {
        pageNum: page,
        pageSize: this.pageSize
      };
      if (!this._utils.isEmpty(this.userId)) {
        params.userId = this.userId;
      }
      if (!this._utils.isEmpty(this.mobileNo)) {
        params.mobileNo = this.mobileNo;
      }
      if (!this._utils.isEmpty(this.nickName)) {
        params.nickName = this.nickName;
      }
      if (!this._utils.isEmpty(this.idCardNo)) {
        params.idCardNo = this.idCardNo;
      }
      if (
        this._utils.getType(this.date) === "Array" &&
        this.date.length === 2
      ) {
        params.startDay = this._utils.format(this.date[0], "yyyy-mm-dd");
        params.endDay = this._utils.format(this.date[1], "yyyy-mm-dd");
      }
      if (!this._utils.isEmpty(this.vip) && this.vip != -1) {
        params.isVip = this.vip;
      }
      console.log("params::", params);
      this.$store.dispatch("GET_USER_LIST", params).then(res => {
        if (res.data.retCode == 0) {
          _this.userList = res.data.data;
          _this.totalCount = res.data.totalCount;
        }
      });
    },
    getAllList() {
      // const _this = this;
      // const page = this.currentPage - 1;
      const params = {
        pageNum: 0,
        pageSize: this.totalCount
      };
      if (!this._utils.isEmpty(this.userId)) {
        params.userId = this.userId;
      }
      if (!this._utils.isEmpty(this.mobileNo)) {
        params.mobileNo = this.mobileNo;
      }
      if (!this._utils.isEmpty(this.nickName)) {
        params.nickName = this.nickName;
      }
      if (!this._utils.isEmpty(this.idCardNo)) {
        params.idCardNo = this.idCardNo;
      }
      if (
        this._utils.getType(this.date) === "Array" &&
        this.date.length === 2
      ) {
        params.startDay = this._utils.format(this.date[0], "yyyy-mm-dd");
        params.endDay = this._utils.format(this.date[1], "yyyy-mm-dd");
      }
      if (!this._utils.isEmpty(this.vip) && this.vip != -1) {
        params.isVip = this.vip;
      }
      console.log("params::", params);
      this.$store.dispatch("GET_USER_LIST", params).then(res => {
        if (res.data.retCode == 0) {
          // _this.userList = res.data.data;
          // _this.totalCount = res.data.totalCount;
          this.exportAllExcel(res.data.data);
        } else {
          this.$message.waring("导出表格发生未知错误！");
        }
      });
    },
    handleCurrentChange(page) {
      console.log("page::", page);
      this.currentPage = page;
      this.getUserList();
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.el-button {
  height: 40px;
}
.edit-item label {
  width: 100px;
  flex-shrink: 0;
  line-height: 40px;
  font-size: 14px;
  color: #666;
}
.table th,
.table td {
  padding: 8px 5px;
  font-size: 14px;
}
.table th {
  color: #333;
  font-weight: bold;
}
.table td {
  color: #666;
}
.table_btn {
  display: inline-block;
  border: 1px solid #ccc;
  padding: 0 10px;
  height: 40px;
  border-radius: 4px;
  line-height: 40px;
  margin-left: 10px;
  cursor: pointer;
}
</style>
